package org.jetlinks.community.mstn.service;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.hswebframework.web.crud.events.EntityBeforeDeleteEvent;
import org.hswebframework.web.crud.events.EntityModifyEvent;
import org.hswebframework.web.crud.events.EntitySavedEvent;
import org.jetlinks.community.mstn.entity.AliasCategoryEntity;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Flux;

@Component
@AllArgsConstructor
@Slf4j
public class AliasCategoryEntityEventHandler {

    private final DeviceAliasService deviceAliasService;
    /**
     * 更新分类时，同时更新数字孪生表的分类名称
     *
     * @param event
     */
    @EventListener
    public void handleUpdate(EntitySavedEvent<AliasCategoryEntity> event) {
        event.async(
            Flux.fromIterable(event.getEntity())
                .flatMap(aliasCategoryEntity ->
                    deviceAliasService.updateCategoryName(aliasCategoryEntity.getId(), aliasCategoryEntity.getName()))
                .then()
        );
    }

    //禁止删除已有使用数字孪生的分类
    @EventListener
    public void handleProtocolDelete(EntityBeforeDeleteEvent<AliasCategoryEntity> event) {
        event.async(
            Flux.fromIterable(event.getEntity())
                .flatMap(aliasCategoryEntity -> deviceAliasService.assertNotReferenced(aliasCategoryEntity.getId()))
        );
    }
}
